package com.module.oa.controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.module.oa.domain.MzActivitiMain;
import com.module.oa.domain.MzActivitiMainInfo;
import com.module.oa.service.IMzActivitiMainInfoService;
import com.module.oa.service.IMzActivitiMainService;
import com.module.oa.util.Util;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.file.utils.FileUploadUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.module.oa.domain.MzAttendanceMain;
import com.module.oa.service.IMzAttendanceMainService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 【请填写功能名称】Controller
 * 
 * @author hezhengxian
 * @date 2023-07-23
 */
@RestController
@RequestMapping("/attendance")
public class MzAttendanceMainController extends BaseController
{
    @Autowired
    private IMzAttendanceMainService mzAttendanceMainService;
    @Autowired
    private IMzActivitiMainService mzActivitiMainService;
    @Autowired
    private IMzActivitiMainInfoService mzActivitiMainInfoService;

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("oa:attendance:list")
    @GetMapping("/list")
    public TableDataInfo list(MzAttendanceMain mzAttendanceMain)
    {
        startPage();
        List<MzAttendanceMain> list = mzAttendanceMainService.selectMzAttendanceMainList(mzAttendanceMain);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("oa:attendance:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MzAttendanceMain mzAttendanceMain)
    {
        List<MzAttendanceMain> list = mzAttendanceMainService.selectMzAttendanceMainList(mzAttendanceMain);
        ExcelUtil<MzAttendanceMain> util = new ExcelUtil<MzAttendanceMain>(MzAttendanceMain.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @RequiresPermissions("oa:attendance:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(mzAttendanceMainService.selectMzAttendanceMainById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @RequiresPermissions("oa:attendance:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MzAttendanceMain mzAttendanceMain)
    {
        mzAttendanceMain.setId(Util.get_radom_id());
        mzAttendanceMain.setApplyTime(new Date());
        // 获取当前登录用户信息
        mzAttendanceMain.setStaffId(SecurityUtils.getLoginUser().getSysUser().getUserId().toString());
        mzAttendanceMain.setStaffName(SecurityUtils.getLoginUser().getSysUser().getNickName());
        // 赋值所属部门编码信息
        mzAttendanceMain.setStandbyOne(SecurityUtils.getLoginUser().getSysUser().getDept().getDeptId().toString());
        // 赋值所属部门名称信息
        mzAttendanceMain.setStandbyTwo(SecurityUtils.getLoginUser().getSysUser().getDept().getDeptName().toString());
        mzAttendanceMain.setBusinessId(Util.get_business_no(Util.ToPinyin(mzAttendanceMain.getBusinessTypeName())));
        return toAjax(mzAttendanceMainService.insertMzAttendanceMain(mzAttendanceMain));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('oa:attendance:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public AjaxResult edit(@RequestBody MzAttendanceMain mzAttendanceMain)
    {
        // 根据下一步人员角色，提交至下一步审批人
        Set<String> s = SecurityUtils.getLoginUser().getRoles();

        System.err.println("当前用户权限：---------------"+s);
        return toAjax(mzAttendanceMainService.updateMzAttendanceMain(mzAttendanceMain));
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("oa:attendance:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(mzAttendanceMainService.deleteMzAttendanceMainByIds(ids));
    }

    /**
     *  上传图片到服务器
     */
    @RequestMapping(value = "/upload/img", method = RequestMethod.POST)
    public AjaxResult upload_image(HttpServletRequest request, HttpServletRequest response) throws IOException {
        String file_path = "D:\\ruoyi\\uploadPath";
        String file_show_path = "http://127.0.0.1:9300/statics";
        AjaxResult ajax = AjaxResult.success();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");// 获取上传文件对象
        //savePath =  this.uploadLocal(file,bizPath);  //调用上传方法返回保存的路径
        String avatar = FileUploadUtils.upload(file_path, file);
        ajax.put("imgUrl", file_show_path+avatar);
        return ajax;
    }

    /**
     * 获取主流程类型
     * @return
     */
    @GetMapping(value = "/businessList")
    public AjaxResult businessList(){
        AjaxResult ajax = AjaxResult.success();
        MzActivitiMain mzActivitiMain = new MzActivitiMain();
        List<MzActivitiMain> list = mzActivitiMainService.selectMzActivitiMainList(mzActivitiMain);
        ajax.put("list",list);
        return ajax;
    }

    /**
     * 获取主流程类型
     * @return
     */
    @GetMapping(value = "/roleList")
    public AjaxResult get_role() throws SQLException, ClassNotFoundException {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> list = Util.getAllRole("select b.* from sys_role b where b.role_key<>'admin' and b.del_flag='0' and b.status='0'");
        ajax.put("list",list);
        return ajax;
    }

    /**
     * 获取流程节点信息
     * @param activitiId
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    @GetMapping(value = "/activitiList/{activitiId}")
    public AjaxResult get_activiti(@PathVariable String activitiId) throws SQLException, ClassNotFoundException {
        AjaxResult ajax = AjaxResult.success();
        List<MzActivitiMainInfo> list = mzActivitiMainInfoService.selectMzActivitiMainInfoByActivitiId(activitiId);
        ajax.put("list",list);
        return ajax;
    }

    /**
     * 根据流程节点获取当前审批人信息
     * @param nodeId
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    @GetMapping(value = "/userInfoList/{nodeId}")
    public AjaxResult getUserInfoByNodeId(@PathVariable String nodeId) throws SQLException, ClassNotFoundException {
        AjaxResult ajax = AjaxResult.success();
        List<SysUser> list = new ArrayList<SysUser>();
        String sql = "";
        // 获取当前申请人信息（角色代码&数据主键id）
        if(nodeId!=null&&!nodeId.equals("")){
            // 连接mysql
            Connection conn = Util.connMysql();
            Statement stmt =conn.createStatement();
            MzAttendanceMain mzAttendanceMain = mzAttendanceMainService.selectMzAttendanceMainById(nodeId.split("&")[1]);
            // 如果当前环节为小组长审批
            if(nodeId.split("&")[0].equals("mz-xzz")){
                sql = "select c.user_id,c.nick_name from sys_user c,(select a.user_id from sys_user_role a where a.role_id in (select b.role_id from sys_role b where b.role_key='"+nodeId.split("&")[0]+"' and b.del_flag='0' and b.status='0')) d where c.user_id=d.user_id and c.del_flag='0' and c.status='0' and c.dept_id='"+nodeId.split("&")[2]+"'";
            }else{
                sql = "select c.user_id,c.nick_name from sys_user c,(select a.user_id from sys_user_role a where a.role_id in (select b.role_id from sys_role b where b.role_key='"+nodeId.split("&")[0]+"' and b.del_flag='0' and b.status='0')) d where c.user_id=d.user_id and c.del_flag='0' and c.status='0'";
            }
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()){
                SysUser sysUser = new SysUser();
                sysUser.setUserId(rs.getLong("user_id"));
                sysUser.setNickName(rs.getString("nick_name"));
                list.add(sysUser);
            }
        }
        ajax.put("list",list);
        return ajax;
    }

}
